package ntd.util;

import ntd.util.fun.ComFun;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class UtilThreadPool {

    public static ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(30);

    /**
     * 交给线程池异步执行
     * @param funEmpty
     */
    public static void run(ComFun.Fun funEmpty) {
        scheduledThreadPool.execute(() -> {
            try {
                funEmpty.accept();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        });
    }

    /**
     * 延时执行
     * @param funEmpty
     * @param delaySeconds
     */
    public static void delayRun(ComFun.Fun funEmpty, long delaySeconds) {
        scheduledThreadPool.schedule(() -> {
            try {
                funEmpty.accept();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }, delaySeconds, TimeUnit.SECONDS);
    }

    /**
     * 循环执行
     * @param funEmpty
     * @param periodSeconds
     */
    public static void periodRun(ComFun.Fun funEmpty, long periodSeconds) {
        periodRun(funEmpty, periodSeconds, 0);
    }

    /**
     * 等待-循环执行
     * @param funEmpty
     * @param periodSeconds
     * @param initialDelaySeconds
     */
    public static void periodRun(ComFun.Fun funEmpty, long periodSeconds, long initialDelaySeconds) {
        scheduledThreadPool.scheduleAtFixedRate(() -> UtilCatch.tryCatchNoRes(funEmpty::accept), initialDelaySeconds, periodSeconds, TimeUnit.SECONDS);
    }

}
